package com.seven.micro_service.Interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seven.micro_service.DAO.AuthorityDAO;
import com.seven.micro_service.tools.JwtUtil;
import com.seven.micro_service.tools.Result;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private JwtUtil jwtUtil;

    @Autowired
    public void setJwtUtil(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    private AuthorityDAO authorityDAO;

    @Autowired
    public void setAuthorityDAO(AuthorityDAO authorityDAO) {
        this.authorityDAO = authorityDAO;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {

        int code;        //状态码 仅错误才返回
        String msg = null;  //状态说明

        // jws设置在Header的Authorization里面
        String token = request.getHeader("Authorization");
        //没有token
        if (token == null || token.equals("")) {
            code = 1004;
            msg = "Not logged in!";
            setResponse(response, new Result<>(code, msg));
            return false;
        }

        //解析token
        JSONObject pojo = jwtUtil.parseJWT(token);

        if (pojo.getBooleanValue("Success")) { // 解析成功
            Claims claims = (Claims) pojo.get("Claims");
            String id = claims.getId();

            //根据uri判断请求的是哪个service 如果请求没有的service 此处为error
            String service = request.getRequestURI().split("/")[1];

            // 与数据库里的比较
            // true 通过验证
            try {
                if (authorityDAO.getAuthorizationWithIdAndService(id, service).isAuthorization()) //数据库中有权限信息且为true
                    return true;
                else {
                    code = 1006;
                    msg = "No permission!";
                    setResponse(response, new Result<>(code, msg));
                    return false;
                }
            } catch (RuntimeException r) {//数据库无表项
                code = 1006;
                msg = "No permission!";
                setResponse(response, new Result<>(code, msg));
                return false;
            }

            // false

        } else { // 解析失败
            code = pojo.getIntValue("ErrCode");
            switch (code) {
                case 1005:
                    msg = "签名过期";
                    break;
                case 1004:
                    msg = "未登录";
                    break;
                default:
                    break;
            }
            setResponse(response, new Result<>(code, msg));
            return false;
        }
    }

    //设置返回值通知前端
    private void setResponse(HttpServletResponse response, Result<Object> result) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
